package com.myalibaba.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class MyService {
    @Resource
    private DataSourceTransactionManager transactionManager;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void druidTest() {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        for (int i = 0; i <10; i++) {
            executorService.submit(() -> {
                System.out.println(123);
            });
        }
        executorService.shutdown();
    }



    public void updateUser() {
        //................省略查询逻辑............

        // 事务管理
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = transactionManager.getTransaction(def);
        int rowsAffected = 0;
        try {
            //如果有if逻辑判断需要结束方法时,记得提交事务
            String sql = "UPDATE `member2` SET `name`=?, `update_time`=now() WHERE `id`=?";
            rowsAffected = jdbcTemplate.update(sql,  "刘彦登测试"+ UUID.randomUUID(),  1);
           // transactionManager.commit(status); // 提交事务
        } catch (Exception e) {
            transactionManager.rollback(status); // 回滚事务
            System.out.println("Exception during transaction: " + e.getMessage());
            throw e;
        } finally {
            System.out.println("Rows affected: " + rowsAffected);
        }
    }

    public void insertUser(String name, String email) {
        String sql = "INSERT INTO member2 (name, email) VALUES (?, ?)";
        int rowsAffected = jdbcTemplate.update(sql, name, email);
        System.out.println("Rows affected: " + rowsAffected);
    }

    //http://localhost:8080/users
    public List<Map<String, Object>> getAllUsers() {
        String sql = "SELECT * FROM member2 limit 1";
        return jdbcTemplate.queryForList(sql);
    }
}
